server {
    server_name {{{String.Coalesce env.BWP_DOMAIN "localhost"}}};

    {{#if (String.Equal env.BWP_ENABLE_SSL "true")}}
        listen {{{String.Coalesce env.RP_PORT "5701"}}} ssl http2;
        #listen [::]:{{{String.Coalesce env.RP_PORT "5701"}}} ssl http2;

        ssl_certificate /etc/bitwarden_passwordless/{{{String.Coalesce env.BWP_SSL_CERT "ssl.crt"}}};
        ssl_certificate_key /etc/bitwarden_passwordless/{{{String.Coalesce env.BWP_SSL_KEY "ssl.key"}}};
        ssl_session_timeout 30m;
        ssl_session_cache shared:SSL:20m;
        ssl_session_tickets off;
        
        {{#if (String.Equal env.BWP_ENABLE_SSL_DH "true")}}
            # Diffie-Hellman parameter for DHE ciphersuites, recommended 2048 bits
            ssl_dhparam /etc/bitwarden_passwordless/{{{String.Coalesce env.BWP_SSL_DH_CERT "dh.pem"}}};
        {{/if}}
    
        ssl_protocols {{{String.Coalesce env.BWP_SSL_PROTOCOLS "TLSv1.2"}}};
        ssl_ciphers "{{{String.Coalesce env.BWP_SSL_CIPHERS "ECDHE-ECDSA-AES256-GCM-SHA384:ECDHE-RSA-AES256-GCM-SHA384:ECDHE-ECDSA-CHACHA20-POLY1305:ECDHE-RSA-CHACHA20-POLY1305:ECDHE-ECDSA-AES128-GCM-SHA256:ECDHE-RSA-AES128-GCM-SHA256:ECDHE-ECDSA-AES256-SHA384:ECDHE-RSA-AES256-SHA384:ECDHE-ECDSA-AES128-SHA256:ECDHE-RSA-AES128-SHA256"}}}";
        
        # Enables server-side protection from BEAST attacks
        ssl_prefer_server_ciphers on;
        
        {{#if (String.Equal env.BWP_ENABLE_SSL_CA "true")}}
            # OCSP Stapling ---
            # Fetch OCSP records from URL in ssl_certificate and cache them
            ssl_stapling on;
            ssl_stapling_verify on;
        
            # Verify chain of trust of OCSP response using Root CA and Intermediate certs
            ssl_trusted_certificate /etc/bitwarden_passwordless/{{{String.Coalesce env.BWP_SSL_CA_CERT "ca.crt"}}};
            resolver 1.1.1.1 1.0.0.1 9.9.9.9 149.112.112.112 valid=300s;
        {{/if}}
    
        include /etc/nginx/security-headers-ssl.conf;
    {{else}}
        listen {{{String.Coalesce env.RP_PORT "5701"}}} default_server;
    {{/if}}

    include /etc/nginx/security-headers.conf;

    {{#if (String.IsNotNullOrWhitespace env.BWP_REAL_IPS)}}
        {{#each (String.Split env.BWP_REAL_IPS ",")}}
            set_real_ip_from {{{String.Trim .}}};
        {{/each}}
        real_ip_header X-Forwarded-For;
        real_ip_recursive on;
    {{/if}}

    location /alive {
        default_type text/plain;
        return 200 $date_gmt;
    }

    {{#if (String.Equal env.BWP_ENABLE_API "true")}}
        location /api/ {
            proxy_pass http://localhost:5000/;
        }
    {{/if}}

    {{#if (String.Equal env.BWP_ENABLE_ADMIN "true")}}
        location / {
            proxy_pass http://localhost:5001/;
        }
    {{else}}
        location / {
            return 404;
        }
    {{/if}}
}
